import requests
import json

from .models import PersonalTask
from zhongbao.settings import to_zhongbao_host, to_zhongbao_token
from task.uploading import wx_robot, async_w


def sync_status(request, tid, sub_status, sub_reason_desc=None):
    task = PersonalTask.objects.get(id=tid)
    task_id = str(task.task_id).replace('2021', '')
    # task_id = tid
    url = '{}api/open/SupportCreateTaskNode/'.format(to_zhongbao_host)
    headers = {
        'Authorization': 'Token {}'.format(to_zhongbao_token),
        'Content-Type': 'application/json'
    }

    data = {
        "task": task_id,
        "sub_status": sub_status,
        "sub_reason_desc": sub_reason_desc,
        "reason": 1,
        "reason_desc": sub_reason_desc
    }
    try:
        resp = requests.post(url, headers=headers, data=json.dumps(data)).json()
        if resp.get('code') not in (200, 201):
            return {"code": 1, "msg": resp.get('msg', '')}
    except:
        return {"code": 1, "msg": "管控平台服务错误"}

    return {"code": 0}


def abort_mission(request, task_id, close_desc=None, marking=True):
    """
    放弃任务同步至管控平台
    """
    task_id = str(task_id).replace('2021', '')
    url = '{}api/open/SupportBusinessView/'.format(to_zhongbao_host)
    headers = {
        'Authorization': 'Token {}'.format(to_zhongbao_token),
        'Content-Type': 'application/json'
    }
    data = {
        "task_id": task_id,
        "marking": marking,
        "close_reason_code": "CT02",
        "close_desc": close_desc
    }
    try:
        print(data)
        resp = requests.put(url, headers=headers, data=json.dumps(data)).json()
        print(resp, '放弃任务结果')
        if resp.get('code') != 200:
            return {"code": 1}
    except:
        return {"code": 1}

    return {"code": 0}


def sync_status1(tid, sub_status, sub_reason_desc=None):
    """
    新版
    :param tid: 任务ID
    :param sub_status: 子状态
    :param sub_reason_desc: 子原因
    :return:
    """
    task = PersonalTask.objects.get(id=tid)
    task_id = str(task.task_id).replace('2021', '')
    url = '{}api/open/SupportCreateTaskNode/'.format(to_zhongbao_host)
    headers = {
        'Authorization': 'Token {}'.format(to_zhongbao_token),
        'Content-Type': 'application/json'
    }

    data = {
        "task": task_id,
        "sub_status": sub_status,
        "sub_reason_desc": sub_reason_desc,
        "reason": 1,
        "reason_desc": sub_reason_desc
    }
    resp = requests.post(url, headers=headers, data=json.dumps(data)).json()
    if resp.get('code') not in (200, 201):
        raise Exception('同步管控平台失败： %s' % resp.get('msg'))


@async_w
def abort_mission1(tid, close_desc=None, marking=True):
    """
    新版
    放弃任务同步至管控平台
    :param tid: 任务ID
    :param close_desc: 放弃原因
    :param marking: 是否兜底
    :return:
    """
    task = PersonalTask.objects.get(id=tid)
    task_id = str(task.task_id).replace('2021', '')
    url = '{}api/open/SupportBusinessView/'.format(to_zhongbao_host)
    headers = {
        'Authorization': 'Token {}'.format(to_zhongbao_token),
        'Content-Type': 'application/json'
    }
    data = {
        "task_id": task_id,
        "marking": marking,
        "close_reason_code": "CT02",
        "close_desc": close_desc
    }
    try:
        resp = requests.put(url, headers=headers, data=json.dumps(data)).json()
        print(resp, '放弃任务结果')
        if resp.get('code') != 200:
            raise Exception('同步管控平台失败： %s' % resp.get('msg'))
    except Exception as e:
        wx_robot("放弃状态同步管控平台错误：%s, 任务ID: %s" % (e, tid))
